$(function () {

  //渲染数据
  function render() {
    $.ajax({
      url: 'http://localhost:3000/heroes',
      type: 'get',
    }).then(function (res) {
      const {err_code, message} = res;
      if (err_code !== 0) return console.log(message);
      let strHtml = ``;
      message.forEach(el => {
        strHtml += `<tr data-id="${el.id}">
      <td>${el.id}</td>
      <td>${el.name}</td>
      <td>${el.age}</td>
      <td>${el.ctime}</td>
      <td>
        <a href="./edit.html?id=${el.id}" class="btn btn-primary">编辑</a>
        &emsp;&emsp;&emsp;
        <button class="btn btn-warning delete">删除</button>
      </td>
    </tr>`;
        $('#t_data').html(strHtml);
      })
    })
  }

  render();

  //删除英雄
  $('#t_data').on('click', '.delete', function () {
    const id = $(this).parents('tr').data('id');
    layer.confirm('您确定要删除该数据吗?', function () {
      $.ajax({
        url: 'http://localhost:3000/heroes/' + id,
        type: 'delete'
      }).then(function (res) {
        const {err_code, message} = res;
        if (err_code !== 0) return layer.msg('删除失败,' + message);
        layer.msg(message);
        render();
      })
    })
  })
})